import 'package:flutter/material.dart';
import 'dart:math' as math;
import '../../models/airplane_model.dart';
import '../../widgets/status_panel.dart';
import '../../widgets/compass_control.dart';

class GravityControlScreen extends StatefulWidget {
  final AirplaneModel model;

  const GravityControlScreen({super.key, required this.model});

  @override
  State<GravityControlScreen> createState() => _GravityControlScreenState();
}

class _GravityControlScreenState extends State<GravityControlScreen> {
  double _pitch = 0.0;
  double _roll = 0.0;
  double _throttle = 0.0;
  bool _isCalibrating = false;
  bool _isFlying = false;

  @override
  Widget build(BuildContext context) {
    final screenSize = MediaQuery.of(context).size;

    return Scaffold(
      appBar: AppBar(
        title: const Text('重力感应模式'),
        actions: [
          IconButton(
            icon: const Icon(Icons.info_outline),
            onPressed: _showHelp,
          ),
        ],
      ),
      body: Column(
        children: [
          // 状态面板
          // StatusPanel(
          //   model: widget.model,
          //   batteryLevel: 78,
          //   signalStrength: 85,
          //   altitude: 25.5,
          //   speed: 12.3,
          // ),
          // 主要内容区域
          Expanded(
            child: Row(
              children: [
                // 左侧：罗盘控制
                Expanded(
                  flex: 3,
                  child: Center(
                    child: CompassControl(
                      pitch: _pitch,
                      roll: _roll,
                      onCalibrate: _calibrate,
                      isCalibrating: _isCalibrating,
                    ),
                  ),
                ),
                // 右侧：控制面板
                Expanded(
                  flex: 2,
                  child: Padding(
                    padding: const EdgeInsets.symmetric(
                      horizontal: 16.0,
                      vertical: 8.0,
                    ),
                    child: Column(
                      mainAxisAlignment: MainAxisAlignment.spaceEvenly,
                      children: [
                        // 飞行状态
                        Container(
                          padding: const EdgeInsets.symmetric(
                            horizontal: 12.0,
                            vertical: 8.0,
                          ),
                          decoration: BoxDecoration(
                            color:
                                _isFlying
                                    ? Colors.green.withOpacity(0.1)
                                    : Colors.grey.withOpacity(0.1),
                            borderRadius: BorderRadius.circular(8),
                          ),
                          child: Row(
                            mainAxisAlignment: MainAxisAlignment.center,
                            children: [
                              Icon(
                                _isFlying
                                    ? Icons.flight_takeoff
                                    : Icons.flight_land,
                                color: _isFlying ? Colors.green : Colors.grey,
                                size: 20,
                              ),
                              const SizedBox(width: 8),
                              Text(
                                '飞行状态: ${_isFlying ? "飞行中" : "已停止"}',
                                style: TextStyle(
                                  fontSize: 14,
                                  fontWeight: FontWeight.bold,
                                  color: _isFlying ? Colors.green : Colors.grey,
                                ),
                              ),
                            ],
                          ),
                        ),
                        // 油门控制
                        Column(
                          mainAxisSize: MainAxisSize.min,
                          crossAxisAlignment: CrossAxisAlignment.start,
                          children: [
                            Row(
                              children: [
                                const Icon(Icons.speed, size: 20),
                                const SizedBox(width: 8),
                                const Text(
                                  '油门控制',
                                  style: TextStyle(fontSize: 14),
                                ),
                              ],
                            ),
                            const SizedBox(height: 4),
                            Row(
                              children: [
                                Expanded(
                                  child: Slider(
                                    value: _throttle,
                                    onChanged: (value) {
                                      setState(() {
                                        _throttle = value;
                                      });
                                    },
                                    min: 0.0,
                                    max: 1.0,
                                    divisions: 10,
                                  ),
                                ),
                                SizedBox(
                                  width: 40,
                                  child: Text(
                                    '${(_throttle * 100).toStringAsFixed(0)}%',
                                    style: const TextStyle(fontSize: 14),
                                    textAlign: TextAlign.end,
                                  ),
                                ),
                              ],
                            ),
                          ],
                        ),
                        // 控制按钮
                        Row(
                          children: [
                            Expanded(
                              child: SizedBox(
                                height: 40,
                                child: ElevatedButton(
                                  onPressed: _toggleFlight,
                                  style: ElevatedButton.styleFrom(
                                    backgroundColor:
                                        _isFlying
                                            ? Colors.orange
                                            : Colors.green,
                                    foregroundColor: Colors.white,
                                    padding: EdgeInsets.zero,
                                  ),
                                  child: Text(
                                    _isFlying ? '降落' : '起飞',
                                    style: const TextStyle(fontSize: 14),
                                  ),
                                ),
                              ),
                            ),
                            const SizedBox(width: 12),
                            Expanded(
                              child: SizedBox(
                                height: 40,
                                child: ElevatedButton(
                                  onPressed: _emergencyStop,
                                  style: ElevatedButton.styleFrom(
                                    backgroundColor: Colors.red,
                                    foregroundColor: Colors.white,
                                    padding: EdgeInsets.zero,
                                  ),
                                  child: const Text(
                                    '紧急停止',
                                    style: TextStyle(fontSize: 14),
                                  ),
                                ),
                              ),
                            ),
                          ],
                        ),
                      ],
                    ),
                  ),
                ),
              ],
            ),
          ),
        ],
      ),
    );
  }

  void _calibrate() {
    setState(() {
      _isCalibrating = true;
    });

    // 模拟校准过程
    Future.delayed(const Duration(seconds: 3), () {
      if (mounted) {
        setState(() {
          _isCalibrating = false;
          // 随机生成一些倾斜角度来模拟传感器数据
          _pitch = (math.Random().nextDouble() * 0.4) - 0.2; // -0.2 到 0.2 之间
          _roll = (math.Random().nextDouble() * 0.4) - 0.2; // -0.2 到 0.2 之间
        });

        ScaffoldMessenger.of(context).showSnackBar(
          const SnackBar(content: Text('校准完成'), duration: Duration(seconds: 2)),
        );
      }
    });
  }

  void _toggleFlight() {
    setState(() {
      _isFlying = !_isFlying;
    });

    ScaffoldMessenger.of(context).showSnackBar(
      SnackBar(
        content: Text(_isFlying ? '飞机起飞' : '飞机降落'),
        duration: const Duration(seconds: 2),
      ),
    );
  }

  void _emergencyStop() {
    setState(() {
      _isFlying = false;
      _throttle = 0.0;
    });

    showDialog(
      context: context,
      builder:
          (context) => AlertDialog(
            title: const Text('紧急停止'),
            content: const Text('已启动紧急停止程序，飞机将安全降落。'),
            actions: [
              TextButton(
                onPressed: () => Navigator.pop(context),
                child: const Text('确认'),
              ),
            ],
          ),
    );
  }

  void _showHelp() {
    showDialog(
      context: context,
      builder:
          (context) => AlertDialog(
            title: const Text('重力感应控制帮助'),
            content: const Column(
              mainAxisSize: MainAxisSize.min,
              crossAxisAlignment: CrossAxisAlignment.start,
              children: [
                Text('通过倾斜手机来控制飞机方向:'),
                SizedBox(height: 8),
                Text('- 向前倾斜: 飞机前进'),
                Text('- 向后倾斜: 飞机后退'),
                Text('- 向左倾斜: 飞机左转'),
                Text('- 向右倾斜: 飞机右转'),
                SizedBox(height: 8),
                Text('使用油门滑块控制飞机高度'),
                SizedBox(height: 16),
                Text('首次使用前请先校准传感器'),
              ],
            ),
            actions: [
              TextButton(
                onPressed: () => Navigator.pop(context),
                child: const Text('了解'),
              ),
            ],
          ),
    );
  }
}
